<script setup>
import { reactive, onMounted, ref } from 'vue';
import FormInput from '../components/FormInput.vue';

let textJson = ref("");
let fromList = reactive([]);

const sx = reactive({
  width: "",
  height: "",
  radius: ""
});

onMounted(() => {
    sx.width = "100px"; 
  sx.height = "30px";
  sx.radius = "4px";
});
function addText() {
  const username = "username" + (fromList.length + 1);
  fromList.push({
    type: 'password',
    username,
    modelValue: '',
    Iwidth: sx.width,
    height: sx.height,
    radius: sx.radius
  });
  textJson.value = JSON.stringify(fromList);
  console.log({ type: 'password', username, modelValue: '' ,width:sx.width,height:sx.height,radius:sx.radius});
}

function showArrFrom() {
  console.log(allValues);
}

const allValues = reactive({});

//更新 allValues 对象
const handleValueUpdate = (index, value) => {
  // 更新 fromList 中的值
  fromList[index].modelValue = value;
  allValues[fromList[index].username] = value;
};

function changeJson() {
  // 解析JSON字符串并更新fromList
  try {
    const newArr = JSON.parse(textJson.value);
    fromList.splice(0, fromList.length, ...newArr.map(item => ({ ...item, modelValue: '' })));
  } catch (error) {
    console.error('解析 JSON 字符串时出错:', error);
  }
}
</script>

<template>
  <div>
    <textarea name="" id="" cols="30" rows="10" v-model="textJson"></textarea>
    <div>
        <el-button @click="changeJson">Json转为表单</el-button>
        <el-button @click="showArrFrom">showArrFrom</el-button>
    </div>

    <div class="changeInput">
        <div><span>宽度</span> <input v-model="sx.width" class="inputSize" type="text"></div>
        <div><span>高度</span> <input v-model="sx.height" class="inputSize" type="text"></div>
        <div><span>圆角</span> <input v-model="sx.radius" class="inputSize" type="text"></div>
  
    </div>
    <el-button @click="addText">添加输入框</el-button>
    <FormInput
      :formList="fromList"
      @update:value="handleValueUpdate"
    ></FormInput>
  </div>
</template>

<style scoped>
    .changeInput{
        display: flex;
    width: 300px;
        padding-bottom: 10px;
    background-color: #fff;
    flex-wrap: wrap;
    justify-content: space-around;
    }
    .changeInput>div{
        
        width: 84px;
        height: 45px;
        border: 1px solid black;
    }
    .inputSize{
        width: 40px;
        height: 40px;
    
    }
</style>